import {Handler} from '@srcTypes/route';
import {Request, Response} from 'express';
import {httpClient} from '@srcUtils/req';
import {HttpUtils} from '@srcUtils/utils';
import {IExplorerNode} from '@srcHandlers/docs/model/docs';
import {resp} from '@srcUtils/resp';
import {lark} from '@/config';

// 获取文档的元信息
const getDocMeta = async (authToken: string, docToken: string) => {
    const requestUrl = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.DOC.DOC_V2_META, [docToken]);
    return await httpClient.get({
        url: requestUrl,
        requireToken: true,
        token: authToken,
    });
};

/**
 * 后端只接收 docToken，由前端处理 url
 * @param{Request} req
 * @param{Response} res
 */
export const getDocMetaReq: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const {docToken} = req.params;
    if (docToken === undefined || docToken === null) {
        res.json(resp.setFail().setMsg('docToken 不合法，请传入正确的 token').collect());
        return;
    }
    const {data} = await getDocMeta(token, docToken) as any;
    if (data.code === 0) {
        res.json(resp.setCode(data.code).setData(data.data).setMsg('ok').collect());
        return;
    }
    res.json(resp.setCode(500).setData(data).collect());
};

/**
 *
 * @param{string} folderToken 文件夹token
 * @param{string} authToken       访问token， tenant_access_token | user_access_token
 */
const getFolderContent = async (folderToken: string, authToken: string) => {
    const folderMetaUrl = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.DRIVE.EXPLORER_V2_FOLDER_META, [folderToken]);
    const folderMetaContentRes = await httpClient.get({
        url: folderMetaUrl,
        requireToken: true,
        token: authToken,
    });
    return (folderMetaContentRes as any).data.data;
};

// 获取根目录文件夹信息
export const getRootFolder: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const folderContentRes = await httpClient.get({
        url: lark.env.api.DOCS_OPEN_API.DRIVE.EXPLORER_V2_ROOT_FOLDER,
        requireToken: true,
        token,
    });
    const folderContent = (folderContentRes as any).data.data;
    const folderToken = folderContent.token;
    const folderMetaContent = await getFolderContent(folderToken, token);
    const resObj: IExplorerNode = {
        name: folderMetaContent.name,
        token: folderMetaContent.token,
        type: 'folder',
        children: [],
        icon: 'el-icon-folder',
        leaf: false,
    };
    res.json(resp.setSuccess().setData(resObj).collect());
};
// 不获取元信息，当触发点击事件时再获取元信息
export const getFolderChildrenWithOutMeta: Handler = async (req: Request, res: Response) => {
    const {folderToken} = req.query;
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const url = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.DRIVE.EXPLORER_V2_FOLDER_CHILDREN, [folderToken]);
    const folderChildrenRes = await httpClient.get({
        url,
        requireToken: true,
        token,
        params: {
            types: ['doc', 'file', 'sheet', 'folder'],
        },
    }).catch((err: Error) => {
        console.log(err);
    });
    const folderChildren = (folderChildrenRes as any).data.data;
    const {children} = folderChildren;
    const resObj: IExplorerNode[] = [];
    for (const nodeToken of Object.keys(children)) {
        const curNode = children[nodeToken];
        const template: IExplorerNode = {
            children: [],
            icon: 'el-icon-folder',
            leaf: false,
            name: '',
            token: '',
            type: '',
        };
        if (curNode.type !== 'folder') {
            template.leaf = true;
            template.icon = 'el-icon-document';
        }
        template.token = curNode.token;
        template.name = curNode.name;
        if (curNode.name.length === 0) {
            template.name = `「无标题」- type=${curNode.type}`;
        }
        template.type = curNode.type;
        resObj.push(template);
    }
    res.json(resp.setSuccess().setData(resObj).collect());
};

export const deleteDoc: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const {docToken} = req.params;
    const url = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.DOC.DOC_V2_FILE, docToken);
    const delRes = await httpClient.delete({
        url,
        requireToken: true,
        token,
    });
    const data = (delRes as any).data;
    res.json(resp.setCode(data.code).setData(data.data).setMsg(data.msg).collect());
};

export const createDoc: Handler = async (req: Request, res: Response) => {
    const token: string = await HttpUtils.getTokenFromRequest(req);
    const {FolderToken} = req.body;
    const createRes = await httpClient.post({
        url: lark.env.api.DOCS_OPEN_API.DOC.DOC_V2_CREATE,
        requireToken: true,
        token,
        data: {
            FolderToken,
            Content: '{}',
        },
    });
    console.log(createRes);
    const data = (createRes as any).data;
    res.json(resp.setCode(data.code).setData(data.data).setMsg(data.msg).collect());
};
